﻿using System;
using UnityEngine;

public abstract class Singleton<T> : MonoBehaviour where T : Singleton<T>
{
    [SerializeField]
    private bool dontDestroyOnLoad = false;

    public static T instance;
    public static T Instance
    {
        get
        {
            if (!instance)
            {
                instance = FindObjectOfType<T>();
#if DEBUG
                Debug.Log("singleton find in scene");

                if (!instance)
                    Debug.LogWarningFormat("singleton {0} not found", typeof(T));
#endif
            }
            return instance;
        }
    }

    public static T TryGet
    {
        get
        {
            if (!instance)
            {
                instance = FindObjectOfType<T>();
                try
                {
                    if (!instance)
                    {
                        throw new NullReferenceException($"singleton {typeof(T)} not found");
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError(e);
                }
            }
            return instance;
        }
    }

    public static void CreateIfNull()
    {
        if (instance == null)
        {
            instance = new GameObject().AddComponent<T>();
#if DEBUG
            Debug.Log("create singleton:" + instance.ToString());
#endif
        }
    }

    private void Awake()
    {
        if (instance)
        {
#if DEBUG
            Debug.LogErrorFormat("duplicated singleton:{0}", typeof(T));
#endif
            Destroy(gameObject);
            return;
        }
        if (dontDestroyOnLoad)
            DontDestroyOnLoad(gameObject);
        instance = GetComponentInChildren<T>();

        OnAwake();
    }

    public void Shutdown()
    {
        instance = null;
        Destroy(gameObject);
    }

    protected virtual void OnAwake()
    {

    }

    protected virtual void OnDestroy()
    {
        if (instance == this)
            instance = null;
    }
}

public abstract class ClassSingleton<T> where T : ClassSingleton<T>, new()
{
    public static T instance;

    static ClassSingleton()
    {
        instance = new T();
        instance.OnAwake();
    }

    protected ClassSingleton() { }

    protected virtual void OnAwake() { }
}